<template>
	<view class="container">
		<view class="order-list">
			<view v-for="(item, index) in orderList" :key="index" class="order-item">
				<view class="order-header">
					<text class="table-name">{{item.table_name}}</text>
					<text :class="['status', item.status === 'using' ? 'using' : 'finished']">
						{{item.status === 'using' ? '使用中' : '已结束'}}
					</text>
				</view>
				<view class="order-info">
					<view class="time-info">
						<text class="label">开始时间：</text>
						<text>{{formatTime(item.start_time)}}</text>
					</view>
					<view class="time-info" v-if="item.end_time">
						<text class="label">结束时间：</text>
						<text>{{formatTime(item.end_time)}}</text>
					</view>
					<view class="time-info">
						<text class="label">使用时长：</text>
						<text>{{calculateDuration(item)}}小时</text>
					</view>
					<view class="amount-info" v-if="item.status === 'using'">
						<text class="label">当前费用：</text>
						<text class="amount">¥{{calculateCurrentAmount(item)}}</text>
					</view>
					<view class="amount-info" v-else-if="item.total_amount > 0">
						<text class="label">消费金额：</text>
						<text class="amount">¥{{item.total_amount}}</text>
					</view>
				</view>
			</view>
		</view>
		<uni-load-more :status="loadMoreStatus"></uni-load-more>
	</view>
</template>

<script>
	import { store } from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				orderList: [],
				page: 1,
				pageSize: 10,
				loadMoreStatus: 'more',
				timer: null
			}
		},
		computed: {
			userInfo() {
				return store.userInfo
			},
			hasLogin() {
				return store.hasLogin
			}
		},
		onLoad() {
			if (this.hasLogin) {
				this.getOrderList()
				// 启动定时器，每分钟更新一次费用
				this.timer = setInterval(() => {
					this.updateCurrentAmounts()
				}, 60000)
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateTo({
						url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
					})
				}, 1500)
			}
		},
		onUnload() {
			// 清除定时器
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
		},
		onPullDownRefresh() {
			this.page = 1
			this.orderList = []
			this.getOrderList()
		},
		onReachBottom() {
			if (this.loadMoreStatus === 'more') {
				this.page++
				this.getOrderList()
			}
		},
		methods: {
			async getOrderList() {
				if (!this.hasLogin) return
				
				this.loadMoreStatus = 'loading'
				try {
					const db = uniCloud.database()
					const dbCmd = db.command
					
					// 构建查询条件
					const whereCondition = {
						user_id: this.userInfo._id
					}
					
					// 查询数据
					const res = await db.collection('yijia-taiqiu-usage')
						.where(whereCondition)
						.orderBy('start_time', 'desc')
						.skip((this.page - 1) * this.pageSize)
						.limit(this.pageSize)
						.get()
					
					console.log('查询结果：', res)
					
					if (!res || !res.result) {
						throw new Error('数据库查询失败')
					}
					
					const data = res.result.data || []
					if (!Array.isArray(data)) {
						console.error('返回数据格式错误：', res)
						throw new Error('数据格式错误')
					}
					
					// 更新列表数据
					if (this.page === 1) {
						this.orderList = data
					} else {
						this.orderList = [...this.orderList, ...data]
					}
					
					// 更新加载状态
					this.loadMoreStatus = data.length < this.pageSize ? 'noMore' : 'more'
					
				} catch (e) {
					console.error('获取订单列表失败：', e)
					uni.showToast({
						title: e.message || '获取订单列表失败',
						icon: 'none',
						duration: 2000
					})
					this.loadMoreStatus = 'more'
				} finally {
					uni.stopPullDownRefresh()
				}
			},
			formatTime(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},
			calculateCurrentAmount(item) {
				if (item.status !== 'using') return 0
				
				const now = new Date().getTime()
				const startTime = new Date(item.start_time).getTime()
				const hours = (now - startTime) / (1000 * 60 * 60)
				
				// 计算费用，向上取整到小时
				const amount = Math.ceil(hours) * item.hourly_rate
				return amount.toFixed(2)
			},
			calculateDuration(item) {
				const endTime = item.end_time ? new Date(item.end_time).getTime() : new Date().getTime()
				const startTime = new Date(item.start_time).getTime()
				const hours = (endTime - startTime) / (1000 * 60 * 60)
				return hours.toFixed(1)
			},
			updateCurrentAmounts() {
				// 强制更新视图
				this.$forceUpdate()
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.order-list {
		.order-item {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			
			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.table-name {
					font-size: 32rpx;
					font-weight: bold;
				}
				
				.status {
					font-size: 28rpx;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					
					&.using {
						color: #007AFF;
						background-color: rgba(0, 122, 255, 0.1);
					}
					
					&.finished {
						color: #999;
						background-color: rgba(153, 153, 153, 0.1);
					}
				}
			}
			
			.order-info {
				font-size: 28rpx;
				color: #666;
				
				.time-info, .amount-info {
					margin-bottom: 10rpx;
					
					.label {
						color: #999;
					}
				}
				
				.amount {
					color: #ff5500;
					font-weight: bold;
				}
			}
		}
	}
</style> 